package com.bestcem.xm.om.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.bp.xm.user.grpc.v1.services.Organization;
import com.bestcem.xm.om.constant.CommonConstant;
import com.bestcem.xm.om.dao.EmailRecordDao;
import com.bestcem.xm.om.dao.EmailTemplateDao;
import com.bestcem.xm.om.dao.SmsRecordDao;
import com.bestcem.xm.om.dao.SmsTemplateDao;
import com.bestcem.xm.om.entity.EmailRecord;
import com.bestcem.xm.om.entity.EmailTemplate;
import com.bestcem.xm.om.entity.SmsRecord;
import com.bestcem.xm.om.entity.SmsTemplate;
import com.bestcem.xm.om.enums.SendChannelEnum;
import com.bestcem.xm.om.enums.TemplateStatusEnum;
import com.bestcem.xm.om.grpc.client.OmOrgGrpcService;
import com.bestcem.xm.om.mq.dto.MsgDataDTO;
import com.bestcem.xm.om.service.OmMqService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * mq消息消费服务
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/16 16:24
 */
@Slf4j
@Service
public class OmMqServiceImpl implements OmMqService {
    @Resource
    private SmsRecordDao smsRecordDao;
    @Resource
    private SmsTemplateDao smsTemplateDao;
    @Resource
    private EmailRecordDao emailRecordDao;
    @Resource
    private EmailTemplateDao emailTemplateDao;
    @Resource
    public OmOrgGrpcService omOrgGrpcService;

    private static final String FORMAT_DATE = "yyyy-MM-dd HH:mm:ss";

    @Override
    public void saveSycData(MsgDataDTO msgDataDTO) {
        if (Objects.isNull(SendChannelEnum.getEnumByIndex(msgDataDTO.getType()))) {
            log.error("[OM] 消息类型为空或未定义，无法继续处理 sendchannel:{}", msgDataDTO.getType());
            return;
        }
        if (StringUtils.isEmpty(msgDataDTO.getReceiver())) {
            log.error("[OM] 接受邮箱号或手机号为空，无法继续处理");
            return;
        }
        if (StringUtils.isEmpty(msgDataDTO.getSendTime())) {
            log.error("[OM] 发送时间为空，无法继续处理");
            return;
        }
        // 将发送时间转换成mongo数据库时间
        LocalDateTime sendTime = cn.hutool.core.date.DateUtil.parseLocalDateTime(msgDataDTO.getSendTime(), FORMAT_DATE);

        // 获取机构信息
        String orgName = null;
        String orgCode = null;
        if (StringUtils.isNotEmpty(msgDataDTO.getOrgId())) {
            Organization organization = omOrgGrpcService.getByIdOrCode(msgDataDTO.getOrgId(), null);
            if (Objects.nonNull(organization)) {
                orgName = organization.getName();
                orgCode = organization.getCode();
            }
        }

        // 根据收件人列表保存信息
        String receiver = msgDataDTO.getReceiver();
        String[] contacts = receiver.split(CommonConstant.SPLIT_COMMA);

        if (SendChannelEnum.SMS.getIndex().equals(msgDataDTO.getType())) {
            // 先保存内容
            SmsTemplate smsTemplate = new SmsTemplate();
            smsTemplate.setContent(msgDataDTO.getContent());
            smsTemplate.setName(CommonConstant.PYTHON_TMPLATE_NAME);
            smsTemplate.setStatus(TemplateStatusEnum.NEW.getIndex());
            smsTemplate.setCreateTime(LocalDateTime.now());
            smsTemplate.setUpdateTime(smsTemplate.getCreateTime());
            String templateId = smsTemplateDao.saveSmsTemplate(smsTemplate);
            // 再保存记录
            for (String contact : contacts) {
                if (StringUtils.isEmpty(contact)) {
                    continue;
                }
                SmsRecord smsRecord = new SmsRecord();
                smsRecord.setOrgName(orgName);
                smsRecord.setOrgCode(orgCode);
                smsRecord.setBatchId(null);
                if (StringUtils.isNotEmpty(msgDataDTO.getOrgId())) {
                    smsRecord.setOrgId(msgDataDTO.getOrgId());
                } else {
                    smsRecord.setOrgId(null);
                }
                if (StringUtils.isNotEmpty(templateId)) {
                    smsRecord.setTemplateId(templateId);
                } else {
                    smsRecord.setTemplateId(null);
                }
                smsRecord.setSmsChannel(msgDataDTO.getSmsChannel());
                smsRecord.setStatus(msgDataDTO.getStatus());
                smsRecord.setSendTime(sendTime);
                smsRecord.setPhone(contact);
                smsRecord.setBatchTopic(msgDataDTO.getName());
                smsRecord.setCreateTime(LocalDateTime.now());
                smsRecord.setUpdateTime(smsRecord.getCreateTime());
                smsRecordDao.insert(smsRecord);
            }
        } else {
            // 先保存内容
            EmailTemplate emailTemplate = new EmailTemplate();
            emailTemplate.setContent(msgDataDTO.getContent());
            emailTemplate.setName(CommonConstant.PYTHON_TMPLATE_NAME);
            emailTemplate.setStatus(TemplateStatusEnum.NEW.getIndex());
            emailTemplate.setCreateTime(LocalDateTime.now());
            emailTemplate.setUpdateTime(emailTemplate.getCreateTime());
            String templateId = emailTemplateDao.saveMailTemplate(emailTemplate);
            // 再保存记录
            for (String contact : contacts) {
                if (StringUtils.isEmpty(contact)) {
                    continue;
                }
                EmailRecord emailRecord = new EmailRecord();
                emailRecord.setId(ObjectId.next());
                emailRecord.setOrgName(orgName);
                emailRecord.setOrgCode(orgCode);
                emailRecord.setBatchId(null);
                if (StringUtils.isNotEmpty(msgDataDTO.getOrgId())) {
                    emailRecord.setOrgId(msgDataDTO.getOrgId());
                } else {
                    emailRecord.setOrgId(null);
                }
                if (StringUtils.isNotEmpty(templateId)) {
                    emailRecord.setTemplateId(templateId);
                } else {
                    emailRecord.setTemplateId(null);
                }
                emailRecord.setStatus(msgDataDTO.getStatus());
                emailRecord.setSendTime(sendTime);
                emailRecord.setEmail(contact);
                emailRecord.setBatchTopic(msgDataDTO.getName());
                emailRecord.setCreateTime(LocalDateTime.now());
                emailRecord.setUpdateTime(emailRecord.getCreateTime());
                emailRecordDao.insert(emailRecord);
            }
        }
    }
}
